package io.renren.modules.app.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.modules.app.entity.WithdrawalsRecordingEntity;
import io.renren.modules.app.entity.vo.QueryRechargeParam;
import io.renren.modules.app.entity.vo.SelectRechargeData;
import io.renren.modules.app.entity.vo.SelectWithdrawalsData;
import io.renren.modules.app.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.app.dao.RechargeDao;
import io.renren.modules.app.entity.RechargeEntity;
import io.renren.modules.app.service.RechargeService;
import org.springframework.transaction.annotation.Transactional;


@Service("rechargeService")
public class RechargeServiceImpl extends ServiceImpl<RechargeDao, RechargeEntity> implements RechargeService {

    @Autowired
    private Snowflake snowflake;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<RechargeEntity> page = this.page(
                new Query<RechargeEntity>().getPage(params),
                new QueryWrapper<RechargeEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public SelectRechargeData queryWithdrawalsRecording(QueryRechargeParam rechargeData) {
        QueryWrapper<RechargeEntity> wrapper = new QueryWrapper<>();
        if (rechargeData.getUserId() != null) {
            wrapper.eq("user_id", rechargeData.getUserId());
        }
        if (StringUtils.isNotEmpty(rechargeData.getRechargeNo())) {
            wrapper.eq("recharge_no", rechargeData.getRechargeNo());
        }
        wrapper.orderByDesc("create_time");
        Page<RechargeEntity> iPage = new Page<>(rechargeData.getPageNum(), rechargeData.getPageSize());
        IPage<RechargeEntity> page = baseMapper.selectPage(iPage, wrapper);
        List<RechargeEntity> list = page.getRecords();

        SelectRechargeData data = new SelectRechargeData();
        data.setTotal(page.getTotal());
        data.setCurrentIndex(page.getCurrent());
        data.setSize(page.getSize());
        data.setPageCount(page.getPages());
        data.setRechargeList(list);
        return data;
    }

    @Transactional
    @Override
    public Integer addRechargeData(RechargeEntity recharge) {
        recharge.setCreateTime(new Date());
        recharge.setRechargeNo("CZ" + String.valueOf(snowflake.nextId()));
        return baseMapper.insert(recharge);
    }

}